package com.huixh.train.member.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.huixh.train.common.context.LoginMemberContext;
import com.huixh.train.common.resp.MemberLoginResp;
import com.huixh.train.utils.security.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author huixh
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(MemberInterceptor.class);
    @Resource
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if (StrUtil.isNotBlank(token)) {
            logger.info("获取会员登录 token :{}", token);
            JSONObject jsonObject = jwtUtil.getPayload(token);
            logger.info("当前会员登陆 :{}", jsonObject);
            MemberLoginResp objectBean = jsonObject.toBean(MemberLoginResp.class);
            LoginMemberContext.setMemberLoginResp(objectBean);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginMemberContext.clear();
    }
}
